package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: DLX
 * @Date: 2021/6/20 16:10
 * @Description:
 **/

@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    @Transactional
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        // 参数校验
        registerRequest.requestCheck();
        // 验证用户名存在
        if (verifyUserNameExist(registerRequest)) {
            response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }
        // 验证邮箱存在
        if (verifyEmailExsit(registerRequest)) {
            response.setCode(SysRetCodeConstants.EMAIL_ALREADY_EXIST.getCode());
            response.setMsg(SysRetCodeConstants.EMAIL_ALREADY_EXIST.getMessage());
            return response;
        }
        // 1.用户表
        String uuid = null;
        try {
            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            String pwd = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
            member.setPassword(pwd);

            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");// 没必要?
            member.setState(1);

            member.setEmail(registerRequest.getEmail());
//            System.out.println(member);
            int effectedRows = memberMapper.insert(member);
            System.out.println(effectedRows);
            if (effectedRows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            // 2.用户验证表
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());

            String key = member.getUsername() + member.getPassword() + UUID.randomUUID();
            uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            int rows = userVerifyMapper.insert(userVerify);
            if (rows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
            return response;
        }
        // 3.激活邮件
        sendMail(uuid,registerRequest);

        // 打印日志
        log.info("注册成功,注册参数request:{}", JSON.toJSONString(registerRequest));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    private void sendMail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("wangkai1955@126.com");
        simpleMailMessage.setTo(request.getEmail());
        simpleMailMessage.setSubject("mall3商城用户激活");
        simpleMailMessage.setText("http://localhost:8080/user/verify?uid="+uuid+"&username="+request.getUserName());
        javaMailSender.send(simpleMailMessage);
    }

    /**
     * 激活邮件验证
     * @param request
     * @return
     */
    @Override
    public UserVerifyResponse verify(UserVerifyRequest request) {
        UserVerifyResponse response = new UserVerifyResponse();
        //参数校验
        try {
            request.requestCheck();
        } catch (Exception e) {
            log.error("MemberServiceImpl.verify Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            return response;
        }
        //修改用户激活表
        Example example = new Example(UserVerify.class);
        String userName = request.getUserName();
        example.createCriteria().andEqualTo("username" , userName).andEqualTo("uuid",request.getUuid());
        UserVerify userVerify = new UserVerify();
        userVerify.setIsVerify("Y");
        int updateRow = userVerifyMapper.updateByExampleSelective(userVerify, example);
        if (updateRow == 0) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        //修改用户表member
        Example example1 = new Example(Member.class);
        example1.createCriteria().andEqualTo("username", userName);
        Member member = new Member();
        member.setUpdated(new Date());
        member.setIsVerified("Y");
        int row = memberMapper.updateByExampleSelective(member,example1);
        if (row == 0) {
            response.setCode(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getCode());
            response.setMsg(SysRetCodeConstants.USERVERIFY_INFOR_INVALID.getMessage());
            return response;
        }
        //激活成功
        log.info("用户激活成功,激活参数:",JSON.toJSONString(request));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    private boolean verifyEmailExsit(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("email", registerRequest.getEmail());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return true;
        }
        return false;
    }

    private boolean verifyUserNameExist(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return true;
//            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
        return false;
    }
}
